<template>
  <div class="comment-item">
    <el-card class="comment-card">
      <!-- 评论头部 -->
      <div class="comment-header-info">
        <div class="user-info">
          <el-avatar
            :size="40"
            :src="comment.userAvatar || defaultAvatar"
            @error="handleAvatarError"
          ></el-avatar>
          <div class="user-details">
            <div class="username">
              {{ comment.username }}
              <span v-if="isReplyContent" class="reply-to-inline">
                回复 <span class="reply-to">@{{ replyToUser }}</span>
              </span>
            </div>
            <div class="comment-meta">
              <!-- 只在主评论显示评分 -->
              <el-rate
                v-if="comment.parentId === 0"
                v-model="comment.rating"
                disabled
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                size="mini"
              ></el-rate>
              <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
        </div>
        <!-- 操作按钮 -->
        <div class="comment-actions" v-if="currentUserId">
          <el-button
            type="text"
            size="mini"
            @click="likeComment"
            :class="{ 'liked': comment.isLiked }"
          >
            <i :class="comment.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
            {{ comment.likes || 0 }}
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="replyComment"
          >
            <i class="el-icon-chat-dot-round"></i>
            回复
          </el-button>
          <el-button
            v-if="comment.userId === currentUserId"
            type="text"
            size="mini"
            @click="deleteComment"
            class="delete-btn"
          >
            <i class="el-icon-delete"></i>
            删除
          </el-button>
        </div>
      </div>
      <!-- 评论内容 -->
      <div class="comment-content">
        <span>{{ replyContent }}</span>
      </div>
      <!-- 评论图片 -->
      <div class="comment-images" v-if="comment.images && comment.images !== 'null'">
        <el-image
          v-for="(image, index) in parseImages(comment.images)"
          :key="index"
          :src="image"
          :preview-src-list="parseImages(comment.images)"
          fit="cover"
          class="comment-image"
        ></el-image>
      </div>
      <!-- 回复区域 -->
      <div class="reply-section" v-if="comment.showReply">
        <el-input
          v-model="comment.replyContent"
          type="textarea"
          :rows="2"
          placeholder="写下你的回复..."
          maxlength="200"
          show-word-limit
        ></el-input>
        <div class="reply-actions">
          <el-button size="mini" @click="submitReply" :loading="comment.replying">
            回复
          </el-button>
          <el-button size="mini" @click="cancelReply">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "CommentItem",
  props: {
    comment: {
      type: Object,
      required: true
    },
    currentUserId: {
      type: [String, Number],
      default: null
    },
    goodsId: {
      type: [String, Number],
      required: true
    },
    isReply: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
    };
  },
  computed: {
    isReplyContent() {
      return /^回复 @[^：:]+[：:]/.test(this.comment.content);
    },
    replyToUser() {
      if (this.isReplyContent) {
        const match = this.comment.content.match(/^回复 @([^：:]+)[：:]/);
        return match ? match[1] : '';
      }
      return '';
    },
    replyContent() {
      if (this.isReplyContent) {
        return this.comment.content.replace(/^回复 @[^：:]+[：:]/, '');
      }
      return this.comment.content;
    }
  },
  methods: {
    // 点赞评论
    likeComment() {
      if (!this.currentUserId) {
        this.$message.warning("请先登录");
        return;
      }

      const url = this.comment.isLiked 
        ? `/comment/unlike/${this.comment.id}?userId=${this.currentUserId}`
        : `/comment/like/${this.comment.id}?userId=${this.currentUserId}`;

      this.$axios
        .post(url)
        .then(resp => {
          if (resp && resp.status === 200 && resp.data && resp.data.success) {
            this.comment.isLiked = !this.comment.isLiked;
            this.comment.likes = this.comment.isLiked ? (this.comment.likes || 0) + 1 : Math.max(0, (this.comment.likes || 0) - 1);
            this.$message.success(resp.data.message || (this.comment.isLiked ? "点赞成功" : "取消点赞成功"));
          } else {
            this.$message.error((resp && resp.data && resp.data.message) || "操作失败");
          }
        })
        .catch(error => {
          console.error("操作失败:", error);
          this.$message.error("操作失败，请稍后重试");
        });
    },

    // 回复评论
    replyComment() {
      if (!this.currentUserId) {
        this.$message.warning("请先登录");
        return;
      }
      this.comment.showReply = true;
    },

    // 提交回复
    submitReply() {
      if (!this.comment.replyContent.trim()) {
        this.$message.warning("请输入回复内容");
        return;
      }
      this.comment.replying = true;
      // 找到主评论id和被回复用户名
      let mainCommentId = this.comment.parentId === 0 ? this.comment.id : this.comment.parentId;
      let replyToUser = this.comment.username;
      const replyData = {
        goodsId: parseInt(this.goodsId),
        userId: parseInt(this.currentUserId),
        username: this.$store.state.user.username || "匿名用户",
        userAvatar: this.$store.state.user.avatar || "",
        content: `回复 @${replyToUser}：${this.comment.replyContent}`,
        rating: 5, // 回复不需要评分
        images: "",
        parentId: mainCommentId
      };
      this.$axios
        .post("/comment/add", replyData)
        .then(resp => {
          if (resp && resp.status === 200) {
            this.$message.success("回复成功");
            this.comment.showReply = false;
            this.comment.replyContent = "";
            this.$emit("reply-added");
          } else {
            this.$message.error("回复失败");
          }
        })
        .catch(error => {
          console.error("回复失败:", error);
          this.$message.error("回复失败");
        })
        .finally(() => {
          this.comment.replying = false;
        });
    },

    // 取消回复
    cancelReply() {
      this.comment.showReply = false;
      this.comment.replyContent = "";
    },

    // 删除评论
    deleteComment() {
      this.$confirm("确定要删除这条评论吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios
          .delete(`/comment/delete/${this.comment.id}?userId=${this.currentUserId}`)
          .then(resp => {
            if (resp && resp.status === 200 && resp.data && resp.data.success) {
              this.$message.success(resp.data.message || "删除成功");
              this.$emit("comment-deleted", this.comment.id);
            } else {
              this.$message.error((resp && resp.data && resp.data.message) || "删除失败");
            }
          })
          .catch(error => {
            console.error("删除评论失败:", error);
            this.$message.error("删除失败");
          });
      }).catch(() => {});
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return "";
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);
      
      if (minutes < 1) return "刚刚";
      if (minutes < 60) return `${minutes}分钟前`;
      if (hours < 24) return `${hours}小时前`;
      if (days < 7) return `${days}天前`;
      
      return date.toLocaleDateString();
    },

    // 解析图片数组
    parseImages(imagesStr) {
      if (!imagesStr || imagesStr === "null") return [];
      try {
        return JSON.parse(imagesStr);
      } catch (e) {
        return [];
      }
    },

    // 处理头像加载错误
    handleAvatarError() {
      return this.defaultAvatar;
    }
  }
};
</script>

<style scoped>
.comment-item {
  margin-bottom: 12px;
}

.comment-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.comment-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.comment-header-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
  text-align: left;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 13px;
  text-align: left;
}

.comment-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  text-align: left;
}

.comment-time {
  font-size: 12px;
  color: #999;
  text-align: left;
}

.comment-actions {
  display: flex;
  gap: 8px;
  text-align: left;
}

.comment-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.comment-actions .liked {
  color: #ff9900;
}

.delete-btn {
  color: #f56c6c;
}

.comment-content {
  margin-bottom: 12px;
  line-height: 1.5;
  color: #333;
  font-size: 14px;
  text-align: left;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px;
}

.comment-image {
  width: 70px;
  height: 70px;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.comment-image:hover {
  transform: scale(1.05);
}

/* 回复区域 */
.reply-section {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: left;
}

.reply-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  text-align: left;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-header-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .comment-actions {
    align-self: flex-end;
  }
  
  .comment-images {
    justify-content: center;
  }
}
.comment-item.reply .comment-card {
  background: #f8f9fa;
  margin-left: 30px;
}
.reply-to-bar {
  padding: 6px 0 2px 0;
  font-size: 13px;
  color: #666;
}
.reply-to {
  color: #409eff;
  font-weight: 500;
}
.reply-to-inline {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}
</style> 